package com.shoes.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shoes.interceptor.anno.CheckAuthorized;
import com.shoes.model.ResponseDO;
import com.shoes.utils.LoggerUtil;
import com.shoes.utils.ResultCode;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @author asen
 */
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    public static final String USER_ID = "user_id";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        boolean result = true;

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        CheckAuthorized checkAuthorized = method.getAnnotation(CheckAuthorized.class);

        /** Check Authorized */
        if(checkAuthorized != null) {
            LoggerUtil.logger.info("************* 进入登录验证拦截器 ************");
            result = checkLogin(request);
            /**验证失败,直接返回结果,提示客户端未登入*/
            if(!result) {
                String userId = request.getParameter(USER_ID);
                JSONObject data = new JSONObject();
                data.put(USER_ID, userId);

                LoggerUtil.logger.info("用户 " + userId + " 验证登入失败");
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(new ResponseDO(ResultCode.USER_NOT_LOGIN, data, "用户未登录")));
                writer.flush();
                writer.close();
            }
        }

        return result;
    }

    /**
     * session中保存user_id与JSESSIONID绑定
     */
    boolean checkLogin(HttpServletRequest request) throws IOException {
        //此时利用session中的user_id 与 request中的user_id 匹配 防止用户操作其他用户的内容
        //对user_id进行验证,session不为空保证已经登入,并保证user_id一致
        HttpSession session = request.getSession(false);
        String userId = request.getParameter(USER_ID);
        if(session != null) {
            Object serverUserId = session.getAttribute(USER_ID);
            if(serverUserId != null && serverUserId.equals(userId)) {
                LoggerUtil.logger.info("用户 " + userId + "验证登入成功");
                return true;
            }
        }
        return false;
    }
}
